package com.enation.app.javashop.base.api;

import com.enation.app.javashop.base.service.WebSocketService;
import com.enation.app.javashop.core.trade.order.model.dos.OrderDO;
import com.enation.app.javashop.framework.context.ApplicationContextHolder;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * webSocketManager 建立连接唯一标识用openId
 * xlg
 * 2020-12-31 17:04
 */
@ServerEndpoint("/websocket/{name}")
@RestController
@RequestMapping("/websocket")
public class WebSocketController {

    private static Logger logger = Logger.getLogger(WebSocketController.class);

    private static WebSocketService webSocketService;

    /**
     * 建立连接
     */
    @OnOpen
    public boolean onOpen(Session session, @PathParam(value = "name") String name) {
        init();
        return webSocketService.onOpen(session, name);
    }

    /**
     * 关闭连接
     * 关闭连接 移除连接人
     */
    @OnClose
    public void onClose(@PathParam(value = "name") String name) {
        init();
        webSocketService.onClose(name);
    }

    /**
     * 推送消息
     */
    @OnMessage
    public void onMessage(String message) {
        init();
        webSocketService.groupSending(message);
    }
    /**
     * 发送消息
     */
    @RequestMapping("websocket_push_message")
    public void test(@RequestBody String message) {
        init();
        webSocketService.webSocketPushMessage(message);
    }

    private synchronized void init(){
       if(webSocketService == null){
           webSocketService = ApplicationContextHolder.getBean(WebSocketService.class);
       }
    }
}
